package com.jie.user.init;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jie.common.util.LogUtil;
import com.jie.component.bloomfilter.core.BloomFilterManager;
import com.jie.component.init.base.AbstractApplicationCommandLineRunnerHandler;
import com.jie.component.lock.annotion.ServiceLock;
import com.jie.component.lock.core.LockType;
import com.jie.component.threadpool.BusinessThreadPool;
import com.jie.model.po.user.User;
import com.jie.user.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

import java.util.List;

import static com.jie.common.constant.LockKey.BLOOM_FILTER_INIT_LOCK;
import static com.jie.common.constant.StrConst.BLOOM_FILTER_USER_REGISTER_PHONE;

/**
 * @author jie
 * @version 1.0 2025-02-13
 */
@Component
@RequiredArgsConstructor
public class BloomFilterInit extends AbstractApplicationCommandLineRunnerHandler {

    private final UserMapper userMapper;

    @Override
    public Integer executeOrder() {
        return 10;
    }

    @Override
    @ServiceLock(lockType = LockType.Reentrant, name = BLOOM_FILTER_INIT_LOCK, keys = "#user_register_phone")
    public void executeInit(ConfigurableApplicationContext context) {
        BusinessThreadPool.execute(() -> initBloomFilter(context));
    }

    private void initBloomFilter(ConfigurableApplicationContext context) {
        LogUtil.initLog("添加已注册手机号的布隆过滤器");
        BloomFilterManager bloomFilterManager = context.getBean(BloomFilterManager.class);
        boolean b = bloomFilterManager.addBloomFilter(BLOOM_FILTER_USER_REGISTER_PHONE, 1000L, 0.01d);
        List<User> users = userMapper.selectList(new QueryWrapper<>());
        if (CollUtil.isNotEmpty(users)) {
            for (User user : users) {
                bloomFilterManager.add(BLOOM_FILTER_USER_REGISTER_PHONE, user.getPhone());
            }
        }
    }
}
